--  NewTeamMemberController

local NewTeamBeInvitedView = import("..views.NewTeamBeInvitedView")
local NewTeamImpeachCaptain = import("..views.NewTeamImpeachCaptain")
local NewTeamMemberView = import("..views.NewTeamMemberView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)
end

function ClassRef:init()
	self._model = app:getInst("TeamModel")

	self._beInvitedPanel = nil -- 被邀请时弹出的UI
end

function ClassRef:listEvent()
	return {
		"onCreateTeam",
		"onTeamUpdate",
		"onTeamMemberUpdate",
		"onTeamLeaderChanged",
		"onTeamNewApplyer"
	}
end


function ClassRef:onEvent(eventName, data)
	if eventName == "onCreateTeam" then -- 整个队伍数据改变
		self:onTeamCreate()
	elseif eventName == "onTeamUpdate" then -- 整个队伍数据改变
		self:onTeamMemberUpdate()
		self:refreshTeamTarget()
	elseif eventName == "onTeamMemberUpdate" then --  队伍成员改变
		self:onTeamMemberUpdate()
	elseif eventName == "onTeamLeaderChanged" then -- 队长改变
		self:onTeamLeaderChanged()
	elseif eventName == "onTeamNewApplyer" then -- 来新申请人
		if self._model:isMyTeam() then
			self._model:reqGetApplicationList()
		end
		self:refreshNewApplyerFlag()
	end
end

function ClassRef:openView(data)
	if self._model:hasTeam() then
		self._model:reqGetTeamInfo() -- 打开UI的时候，主动拉取一次队伍数据
	end
	if self._model:isMyTeam() then -- 打开UI的时候，队长拉取一次申请列表
		self._model:reqGetApplicationList()
	end

	if cc.isDead(self._view) then
		self._view = NewTeamMemberView.new(app.mvc.VIEWTYPE_BLUR, data)
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self._onOperate))

		local openBtn = app:sendMsg("IMRoomController", "getIMOpenBtn")
		if openBtn then
			self._view:addChild(openBtn, 2)
		end
	end
	self:addChild(self._view, data)

	self:refreshTeamMember()
	self:refreshTeamTarget()
	self:refreshAutoFollowStatus()
	self:refreshCompatPower()
	self:refreshBtnShownAccordingToIsLeader()
	self:refreshBtnShownWithTeamGrade()

	self._view:show()
end
function ClassRef:closeView(data)
	if self._view then
		self:removeChild(self._view, data)
		self:clearView()
	end
end
function ClassRef:clearView(data)
	if self._view then self._view = nil end
end

------------------------------ view logic ---------------------------------
-- 队伍创建
function ClassRef:onTeamCreate()
	-- 王朝、冠军赛、挑战赛、精英赛 界面创建队伍不显示
	if app:sendMsg("DynastyBattleController", "isViewAlive") then return end
	if app:sendMsg("PvpChampionController", "isViewAlive") then return end
	if app:sendMsg("PvpChallengeController", "isChallengeShow") then return end
	if app:sendMsg("PvpEliteController", "isEliteMatchSeekShow") then return end

	local team = self._model:getTeam()
	if not team:hasTeamTarget() then
		self:openView()
	end
end

-- 整个队伍更新
function ClassRef:onTeamUpdate()
	self:refreshTeamMember()
	self:refreshAutoFollowStatus()
	self:refreshTeamTarget()
	self:refreshCompatPower()
	self:refreshBtnShownAccordingToIsLeader()
	self:refreshBtnShownWithTeamGrade()
end

-- 成员相关的任何变化（ 进出、跟随、队长改变、、、 ）
function ClassRef:onTeamMemberUpdate()
	self:refreshTeamMember()
	self:refreshAutoFollowStatus()
	self:refreshCompatPower()
	self:refreshBtnShownAccordingToIsLeader()
	self:refreshBtnShownWithTeamGrade()
end

-- 队长改变
function ClassRef:onTeamLeaderChanged()
	self:refreshTeamMember()
	self:refreshAutoFollowStatus()
	self:refreshBtnShownAccordingToIsLeader()
	self:refreshBtnShownWithTeamGrade()
end

-- 刷新队伍成员
function ClassRef:refreshTeamMember()
	if not self:isViewAlive() then return end
	self._view:refreshTeamMember( self._model:getTeam() )

	local maxNum = self._model:getMaxNumOfMembersByTeamGarde()
	local leaderPartnerInfo = self._model:getLeaderPartnerInfo()
	self._view:refreshPartnerInfo( maxNum, leaderPartnerInfo )
end

-- 刷新队伍目标
function ClassRef:refreshTeamTarget()
	if not self:isViewAlive() then return end

	local teamTargetVo = self._model:getTeamTargetVo()
	self._view:setTarget( teamTargetVo and teamTargetVo:getFullName() or "" )
end

-- 刷新跟随状态标记
function ClassRef:refreshAutoFollowStatus()
	if not self:isViewAlive() then return end

	local isLeader = self._model:isLeader()
	local isAutoFollow = self._model:isWithTeam()
--    local isAlwaysFollow = self._model:getAlwaysWithTeam()
	self._view:refreshTeamFollow( self._model:getTeam() )
	if isLeader then
		self._view:setAutoFollowBtnClickEnabled( true )
	else
        self._view:setAutoFollowStatus(isAutoFollow)
--		self._view:setAutoFollowStatus(isAutoFollow or isAlwaysFollow)

		if self._model:isTeamNormal() then -- 队伍状态为正常？
			local mapId = MapManager:getMapId()
			if mapId and mapId == tonumber(S("lionHeartHornMapID")) then -- 所处场景为狮心号角？
				self._view:setAutoFollowBtnClickEnabled( false )
			elseif app:getInst("DynastyMapModel"):isDynastyMap() then -- 所处公会战场
				self._view:setAutoFollowBtnClickEnabled(false)
			else
				self._view:setAutoFollowBtnClickEnabled( true )
			end
		else
			self._view:setAutoFollowBtnClickEnabled( false )
		end
	end
end

-- 刷新队伍战斗力
function ClassRef:refreshCompatPower()
	if not self:isViewAlive() then return end

	local combat = self._model:getTeamTotalCapacity(true)
	self._view:refreshTeamCombatPower( combat )
end

-- 根据 是否队长 刷新队伍可操作性按钮显示状态
function ClassRef:refreshBtnShownAccordingToIsLeader()
	if not self:isViewAlive() then return end
	self._view:btnShownAccordingToIsLeader( self._model:isLeader() )
end

-- 根据 TeamGrade 刷新 队伍/军团 按钮显示状态
function ClassRef:refreshBtnShownWithTeamGrade()
	if not self:isViewAlive() then return end
	self._view:refreshBtnShownWithTeamGrade( self._model:isLeader(), self._model:getTeamGrade() )
end

-- 切换队伍性质(队伍/军团)
function ClassRef:changeTeamGrade( inviteInfoTemp )
	if not self:isViewAlive() then return end

	local nowTeamGrade = self._model:getTeamGrade() -- 修改之前的队伍类型
	local newTeamGrade = nil
	if 1 == nowTeamGrade then
		newTeamGrade = 0
	else
		newTeamGrade = 1
	end

	if 1 == nowTeamGrade and self._model:getMaxNumOfMembersByTeamGarde( newTeamGrade ) < self._model:getMemberNum() then -- 之前是军团且成员个数超过队伍允许上限
		display.pushToast( L("lua_code_text_480") )
		return
	end
	self._model:reqUpdateTeamGrade( newTeamGrade )
end

-- 切换自动跟随状态
function ClassRef:teamMemberChangeAutoFollow()
	if self._model:isTeamNormal() then -- normal
		local mapId = MapManager:getMapId()
		if mapId and mapId == tonumber(S("lionHeartHornMapID")) then -- 所处场景为狮心号角？
			display.pushToast( L("tips_3000401") )
			return
		end
	else
		display.pushToast( L("tips_3000401") )
		return
	end

	local oldFollowStatus = self._model:isWithTeam()
	self._model:reqFollowLeader( not oldFollowStatus )

	--设置一直跟随队伍，直到自己主动取消
--    self._model:setAlwaysWithTeam(not oldFollowStatus)
end

-- 新申请人new标记
function ClassRef:refreshNewApplyerFlag()
	if not self:isViewAlive() then return end
	self._view:refreshNewApplyerFlag( self._model:isNewApplyerFlag() )
end

-- 反向打开队伍查找器
function ClassRef:relocateToTeamSearching()
	if not DungeonManager:isInDungeon() then
		self:closeView() -- 关闭自己
	end
	
	local teamTargetVo = self._model:getTeamTargetVo()
	local params = teamTargetVo and teamTargetVo:getTeamMatchParams()
	UIHandler:handleMessage({id=Constant.FUNC_TYPE_TEAMMATCHING_TEAM, mode="open", data=params})
end

function ClassRef:_closeImpeachView(data)
    if self._ImpeachCaptainView then
        self._ImpeachCaptainView:removeScheduler()
        self:removeChild(self._ImpeachCaptainView, data)
        self:_clearImpeachView()
    end
end

function ClassRef:_clearImpeachView()
    if self._ImpeachCaptainView then self._ImpeachCaptainView = nil end
end

function ClassRef:showTeamImpeachView(params)
    if cc.isDead(self._ImpeachCaptainView) then
        self._ImpeachCaptainView = NewTeamImpeachCaptain.new()
        self._ImpeachCaptainView:onOperate(handler(self, self._onOperate))
        self._ImpeachCaptainView:onCloseView(handler(self, self._closeImpeachView))
        self._ImpeachCaptainView:onClearView(handler(self, self._clearImpeachView))
        self:addChild(self._ImpeachCaptainView)
    end

    local team = self._model:getTeam()
    self._ImpeachCaptainView:refreshContents(params, team)
    self._ImpeachCaptainView:show()
end

-------------------------------------------------------------->>>>>>>>>>>>>>>>>>> 邀请相关
function ClassRef:closeBeInvitedView(data)
	if self._beInvitedPanel then
		self:removeChild(self._beInvitedPanel, data)
		self:clearBeInvitedViewView()
	end
end
function ClassRef:clearBeInvitedViewView(data)
	if self._beInvitedPanel then self._beInvitedPanel = nil end
end
-- 接到邀请
-- params = {
-- 	remindId = 100411,
-- 	dataTemp = InviteInfo pb结构
-- 	teamTarget = TeamTargetVo／nil
-- }
function ClassRef:beingInvited( params )
	if BattleManager:isBattle() then -- 战斗中
		self._model:reqApplyJoinTeamByInvited( false, params.dataTemp, 1 )
		return
	elseif StoryManager:isEnterStoryMode() then -- 剧情中
		self._model:reqApplyJoinTeamByInvited( false, params.dataTemp, 2 )
		return
	end

	if cc.isDead( self._beInvitedPanel ) then
		self._beInvitedPanel = NewTeamBeInvitedView.new()
		self._beInvitedPanel:onCloseView(handler(self, self.closeBeInvitedView))
		self._beInvitedPanel:onClearView(handler(self, self.clearBeInvitedViewView))
		self._beInvitedPanel:onOperate(handler(self, self._onOperate))
		self:addChild(self._beInvitedPanel)
	end
	self._beInvitedPanel:refreshContent( params )
	self._beInvitedPanel:show()
end
--------------------------------------------------------------<<<<<<<<<<<<<<<<<<<<<<<<<<<

function ClassRef:_onOperate( op, ... )
	-- dump({...}, "NewTeamMemberController.onOperate data")

	local data = ...
	if op == "TeamMember_showApplyList" then -- 弹出队伍申请列表
		if self._model:isLeader() then
			app:sendMsg("NewTeamApplyController", "openView", { 2 } ) -- 弹出标签2-申请标签
		else
			display.pushToast( L("lua_code_text_155") )
		end
	elseif op == "MemberInfoPanel_partnerOp" then -- 操作随从
		if self._model:isMyTeam() then
			local pos, uid = ...
			UIHandler:showHeadMenu( { type=Enums.MenuType.teamPartner, pos=pos, uid=uid } )
		else
			display.pushToast( L("lua_code_text_503") )
		end
	elseif op == "MemberInfoPanel_robotOp" then -- 操作机器人
		local pos, robotBaseInfo = ...
		if self._model:isMyTeam() then
			UIHandler:showHeadMenu( { type = Enums.MenuType.teamRobot, pos = pos, attr=robotBaseInfo } )
		end
	elseif op == "TeamMember_showTeamSettingUI" then -- 展开队伍设置UI
		app:sendMsg("NewTeamSettingController", "openView")
	elseif op == "MemberInfoPanel_openInvitePanel" then -- 弹出邀请panel
		app:sendMsg("NewTeamApplyController", "openView", { 1 } ) -- 弹出标签1-邀请标签
	elseif op == "TeamMember_quitTeam" then -- 退出队伍
		self._model:reqQuitTeam()
	elseif op == "TeamMember_changeTeamGrade" then -- 改变队伍类型（队伍/军团）
		if self._model:isMyTeam() then
			self:changeTeamGrade()
		else
			display.pushToast( L("lua_code_text_522") )
		end
	elseif op == "TeamMember_changeAutoFollowStatus" then -- 队员切换自动跟随状态
		self:teamMemberChangeAutoFollow()
	elseif op == "TeamMember_inviteFollow" then -- 召集队友
		self._model:reqInviteFollow()
	elseif op == "TeamMember_relocateToTeamSearching" then -- 反向打开队伍查找器
		self:relocateToTeamSearching()
	elseif op == "BeInvited_sure" then -- 收到邀请、回复确定
		-- 以下：移除桌面通知
		UIHandler:getDesktopController():removeFourthTips( data )
		self._model:reqApplyJoinTeamByInvited( true, data.dataTemp, 0 )
	elseif op == "BeInvited_cancel" then -- 收到邀请、回复拒绝
		-- 以下：移除桌面通知
		UIHandler:getDesktopController():removeFourthTips( data )
		self._model:reqApplyJoinTeamByInvited( false, data.dataTemp, 0 )
    elseif op == "ImpeachResponses" then    --回复更换队长
        self._model:reqImpeachLeaderResponses(data)
	end
end

return ClassRef
